var express = require('express');
var router = express.Router();
const { userModel, listModel, cartModel } = require('../db');

// 获取用户信息
router.get('/user/:id', async (req, res) => {
  try {
    const user = await userModel.findById(req.params.id);
    if (!user) {
      return res.status(404).json({ message: 'User not found' });
    }
    res.json(user);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

// 获取商品列表
router.get('/products', async (req, res) => {
  try {
    const products = await listModel.find().populate('user_id');
    res.json(products);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

// 添加到购物车
router.post('/cart/add', async (req, res) => {
  try {
    const { productId, userId } = req.body;
    const newCartItem = new cartModel({
      cart_id: productId,
      user_id: userId,
      state: 1 // 1表示在购物车中
    });
    await newCartItem.save();
    
    // 更新用户的购物车数组
    await userModel.findByIdAndUpdate(userId, {
      $push: { cart: productId }
    });
    
    res.json({ success: true, message: 'Added to cart' });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

module.exports = router;
